<?php

/**
 * Here is your custom functions.
 */

use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use support\Log;

/**
 * 接口调用 function
 *
 * @param array $msg
 * @return void
 */
function AsynChatGptApi(array $msg, $connection, $to_client_id): void
{
    $client = new Client([
        "headers" => [
            "Host" => "lemurchat.anfans.cn",
            "User-Agent" => "Mozilla/5.0 (Linux;Android 13;22021211RC) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/110.0.0.0 MobileSafari/537.36"
        ],
    ]);
    $response = $client->requestAsync(
        'POST',
        'http://lemurchat.anfans.cn:80/api/chat/conversation-trial',
        [
            'stream' => true,
            "json" => [
                "messages" => json_encode($msg, 320)
            ],
            'progress' => function ($bytesTransferred, $size) use (&$fileSize) {
                $fileSize = $size; // 更新已传输的总字节数
            }
        ]
    );
    $response->then(function (\GuzzleHttp\Psr7\Response $res) use (&$fileSize, $connection, $to_client_id) {
        $stream = $res->getBody();
        $i = $fileSize;
        $str = "";
        while (!$stream->eof()) {
            $str .= $stream->read(1);
            if ($i != $fileSize && $i > 200) {
                $arr = GptData($str);
                foreach ($arr as $k => $v) {
                    $connection->send(json_encode([
                        "client_id" => $to_client_id,
                        "msg" => $v
                    ], 320));
                }
                $str = "";
            }
            $i = $fileSize;
        }
    })->wait();
}

/**
 * 删除空格 function
 *
 * @param string $str
 * @return string
 */
function trimall(string $str): string
{
    $limit = array(" ", "　", "\t", "\n", "\r", " ");
    $rep = array("", "", "", "", "", "");
    return str_replace($limit, $rep, $str);
}

/**
 * gpt返回文本整理 function
 *
 * @param string $text
 * @return array
 */
function GptData(string $text): array
{
    // var_dump($text);
    if (substr($text, -1) == 'i') {
        $text = substr_replace($text, '', -1, 1);
    }
    if (substr(trim($text), 0, 1) == 'd') {
        $text = "i" . trim($text);
    }
    $arr = [];
    foreach (explode("\n", $text) as $k => $v) {
        if (preg_match("/data:\s+(.*)/", $v, $matches)) {

            /* $str = str_replace('\"', '"', $matches[1]);
            $str = str_replace('\n\n', '', $str);
            $str = str_replace('\\\\n', "\\n", $str);

            $str = str_replace('}data: {', '},{', $str);
            $str = str_replace('data: {', '[{', $str);
            $str = str_replace('}","code"', '}]","code"', $str);


            $str = str_replace('"data":"[{', '"data":[{', $str);
            $str = str_replace('}]","code"', '}],"code"', $str);

            $str = str_replace('data: [DONE]"', ']', $str);
            $str = str_replace('\"', '"', $str);
            
            $arr[] = json_decode($str, true); */
            if (isset($matches[1])) {
                $arr[] = $matches[1];
            }
        }
    }
    return $arr;
}
/* function GptData(string $text): array
{
    preg_match("/data:\s+(.*)/", $text, $matches);
    
    $str = str_replace('\"', '"', $matches[1]);
    $str = str_replace('\n\n', '', $str);
    $str = str_replace('\\\\n', "\\n", $str);

    $str = str_replace('}data: {', '},{', $str);
    $str = str_replace('data: {', '[{', $str);
    $str = str_replace('}","code"', '}]","code"', $str);


    $str = str_replace('"data":"[{', '"data":[{', $str);
    $str = str_replace('}]","code"', '}],"code"', $str);

    $str = str_replace('data: [DONE]"', ']', $str);
    $str = str_replace('\"', '"', $str);
    // var_dump($str);
    // $str = str_replace('\"', '\\"', $str);
    // var_dump()
    $data = json_decode($str, true);
    // print_r($data);
    return $data;
} */
